import { Injectable, Logger } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

export interface JwtPayload {
  username: string;
  sub: number; // 用户ID
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(JwtStrategy.name);

  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'secretKey', // 在生产环境中应该使用环境变量
    });
  }

  // 验证JWT有效后返回用户信息
  async validate(payload: JwtPayload) {
    this.logger.debug(`JWT Payload: ${JSON.stringify(payload)}`);

    // 确保payload中有必要的字段
    if (!payload.sub || !payload.username) {
      this.logger.error(`Invalid payload: missing required fields`);
      return null;
    }

    // 注意：这里返回的对象字段名必须与RequestWithUser接口中定义的一致
    // 用户ID存储在payload的sub字段中，需要映射到userId
    const user = {
      userId: payload.sub,
      username: payload.username,
    };

    this.logger.debug(`Extracted user: ${JSON.stringify(user)}`);
    return user;
  }
}
